from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from apps.activity.serializers import *
from utils.page import PageNum


class GatheringsView(ModelViewSet):
    # 活动
    serializer_class = ActiveSerializer
    queryset = Gathering.objects.all()
    pagination_class = PageNum

    def list(self, request, *args, **kwargs):
        # 活动列表
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            data = serializer.data
            for data_dict in data:
                d_list = data_dict.pop('users')
                u_list = []
                for id_dict in d_list:
                    u_list.append(id_dict.get('id'))
                    # d_list.remove(id_dict.get('id'))
                data_dict['users'] = u_list

            return self.get_paginated_response(serializer.data)

    def retrieve(self, request, *args, **kwargs):
        # 活动详情
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = serializer.data
        d_list = data.pop('users')
        u_list = []
        for id_dict in d_list:
            u_list.append(id_dict.get('id'))
            # d_list.remove(id_dict.get('id'))
        data['users'] = u_list
        return Response(data)


class ActiveAPIViw(APIView):
    # permission_classes = [IsAuthenticated]

    def post(self, request, id):
        user = request.user
        gather = Gathering.objects.get(id=id)
        # gather.users.add(user) # 添加数据
        # gather.users.remove(user) 删除数据
        count = Gathering.objects.filter(users__in=(user,), id=id).count()
        if count != 0:
            gather.users.remove(user)
            return Response({'success': True,
                             'message': '取消报名'})
        else:
            gather.users.add(user)
            return Response({'success': True,
                             'message': '报名成功'})
